package com.styletransfer.service;

import com.styletransfer.exception.BusinessException;
import com.styletransfer.mapper.NotificationMapper;
import com.styletransfer.mapper.UserMapper;
import com.styletransfer.model.ApiResponse;
import com.styletransfer.model.Notification;
import com.styletransfer.model.PageResponse;
import com.styletransfer.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 消息通知服务
 */
@Service
public class NotificationService {

    private static final Logger logger = LoggerFactory.getLogger(NotificationService.class);

    @Autowired
    private NotificationMapper notificationMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    /**
     * 创建新作品通知
     *
     * @param workId 作品ID
     * @param workTitle 作品标题
     * @param fromUserId 发布作品的用户ID
     * @return 创建的通知
     */
    @Transactional
    public Notification createNewWorkNotification(Long workId, String workTitle, Long fromUserId) {
        // 获取用户关注者列表，为每个关注者创建通知
        List<Long> followers = userMapper.findFollowersByUserId(fromUserId);
        if (followers == null || followers.isEmpty()) {
            return null;
        }

        // 获取发布作品的用户名
        User fromUser = userMapper.findById(fromUserId);
        String fromUsername = fromUser != null ? fromUser.getUsername() : "用户";

        // 为每个关注者创建通知
        for (Long followerId : followers) {
            Notification notification = new Notification();
            notification.setUserId(followerId);
            notification.setFromUserId(fromUserId);
            notification.setType("new_work");
            notification.setContent(fromUsername + " 发布了新作品：" + (workTitle != null ? workTitle : "未命名作品"));
            notification.setResourceId(workId);
            notification.setIsRead(0);
            notification.setCreateTime(new Date());
            notification.setUpdateTime(new Date());

            notificationMapper.insert(notification);
        }

        return null;
    }

    /**
     * 创建新专辑通知
     *
     * @param albumId 专辑ID
     * @param albumTitle 专辑标题
     * @param fromUserId 发布专辑的用户ID
     * @return 创建的通知
     */
    @Transactional
    public Notification createNewAlbumNotification(Long albumId, String albumTitle, Long fromUserId) {
        // 获取用户关注者列表，为每个关注者创建通知
        List<Long> followers = userMapper.findFollowersByUserId(fromUserId);
        if (followers == null || followers.isEmpty()) {
            return null;
        }

        // 获取发布专辑的用户名
        User fromUser = userMapper.findById(fromUserId);
        String fromUsername = fromUser != null ? fromUser.getUsername() : "用户";

        // 为每个关注者创建通知
        for (Long followerId : followers) {
            Notification notification = new Notification();
            notification.setUserId(followerId);
            notification.setFromUserId(fromUserId);
            notification.setType("new_album");
            notification.setContent(fromUsername + " 发布了新专辑：" + (albumTitle != null ? albumTitle : "未命名专辑"));
            notification.setResourceId(albumId);
            notification.setIsRead(0);
            notification.setCreateTime(new Date());
            notification.setUpdateTime(new Date());

            notificationMapper.insert(notification);
        }

        return null;
    }

    /**
     * 创建新评论通知
     *
     * @param workId 作品ID
     * @param workTitle 作品标题
     * @param commentId 评论ID
     * @param commentContent 评论内容
     * @param fromUserId 评论者ID
     * @param toUserId 作品所有者ID
     * @return 创建的通知
     */
    @Transactional
    public Notification createNewCommentNotification(String type, Long workId, String workTitle, Long commentId,
                                                    String commentContent, Long fromUserId, Long toUserId) {
        // 如果评论者是作品所有者，则不需要创建通知
        if (fromUserId.equals(toUserId)) {
            return null;
        }

        // 获取评论者用户名
        User fromUser = userMapper.findById(fromUserId);
        String fromUsername = fromUser != null ? fromUser.getUsername() : "用户";

        // 创建通知
        Notification notification = new Notification();
        notification.setUserId(toUserId);
        notification.setFromUserId(fromUserId);
        notification.setType(type);
        notification.setContent(fromUsername + " 评论了你的作品 " + (workTitle != null ? workTitle : "未命名作品") +
                              "：" + (commentContent.length() > 30 ? commentContent.substring(0, 30) + "..." : commentContent));
        notification.setResourceId(workId);
        notification.setIsRead(0);
        notification.setCreateTime(new Date());
        notification.setUpdateTime(new Date());

        notificationMapper.insert(notification);

        return notification;
    }

    /**
     * 获取用户通知列表
     *
     * @param userId 用户ID
     * @param page 页码
     * @param size 每页大小
     * @return 通知列表
     */
    public ApiResponse<PageResponse<Notification>> getUserNotifications(Long userId, int page, int size) {
        try {
            // 计算偏移量
            int offset = (page - 1) * size;

            // 查询通知
            List<Notification> notifications = notificationMapper.findByUserId(userId, offset, size);

            // 查询总数
            int total = notificationMapper.countByUserId(userId);

            // 构建分页响应
            PageResponse<Notification> pageResponse = new PageResponse<>();
            pageResponse.setList(notifications);
            pageResponse.setTotal((long) total);
            pageResponse.setPages(page);
            pageResponse.setTotal((long) size);

            return ApiResponse.success(pageResponse);
        } catch (Exception e) {
            logger.error("获取用户通知列表失败: " + e.getMessage(), e);
            return ApiResponse.error("获取用户通知列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户未读通知数量
     *
     * @param userId 用户ID
     * @return 未读通知数量
     */
    public ApiResponse<Integer> getUnreadCount(Long userId) {
        try {
            int count = notificationMapper.countUnreadByUserId(userId);
            return ApiResponse.success(count);
        } catch (Exception e) {
            logger.error("获取未读通知数量失败: " + e.getMessage(), e);
            return ApiResponse.error("获取未读通知数量失败: " + e.getMessage());
        }
    }

    /**
     * 标记通知为已读
     *
     * @param id 通知ID
     * @param userId 用户ID
     * @return 操作结果
     */
    @Transactional
    public ApiResponse<Void> markAsRead(Long id, Long userId) {
        try {
            // 检查通知是否存在
            Notification notification = notificationMapper.findById(id);
            if (notification == null) {
                throw new BusinessException("通知不存在");
            }

            // 检查是否有权限标记
            if (!notification.getUserId().equals(userId)) {
                throw new BusinessException("没有权限标记此通知");
            }

            // 标记为已读
            notificationMapper.markAsRead(id);

            return ApiResponse.success();
        } catch (Exception e) {
            logger.error("标记通知已读失败: " + e.getMessage(), e);
            return ApiResponse.error("标记通知已读失败: " + e.getMessage());
        }
    }

    /**
     * 标记所有通知为已读
     *
     * @param userId 用户ID
     * @return 操作结果
     */
    @Transactional
    public ApiResponse<Void> markAllAsRead(Long userId) {
        try {
            notificationMapper.markAllAsRead(userId);
            return ApiResponse.success();
        } catch (Exception e) {
            logger.error("标记所有通知已读失败: " + e.getMessage(), e);
            return ApiResponse.error("标记所有通知已读失败: " + e.getMessage());
        }
    }

    /**
     * 删除通知
     *
     * @param id 通知ID
     * @param userId 用户ID
     * @return 操作结果
     */
    @Transactional
    public ApiResponse<Void> deleteNotification(Long id, Long userId) {
        try {
            // 检查通知是否存在
            Notification notification = notificationMapper.findById(id);
            if (notification == null) {
                throw new BusinessException("通知不存在");
            }

            // 检查是否有权限删除
            if (!notification.getUserId().equals(userId)) {
                throw new BusinessException("没有权限删除此通知");
            }

            // 删除通知
            notificationMapper.delete(id);

            return ApiResponse.success();
        } catch (Exception e) {
            logger.error("删除通知失败: " + e.getMessage(), e);
            return ApiResponse.error("删除通知失败: " + e.getMessage());
        }
    }

    /**
     * 创建通知
     *
     * @param notification 通知对象
     * @return 创建的通知
     */
    @Transactional
    public ApiResponse<Notification> createNotification(Notification notification) {
        try {
            // 设置默认值
            notification.setIsRead(0);
            notification.setCreateTime(new Date());
            notification.setUpdateTime(new Date());

            // 插入通知
            notificationMapper.insert(notification);

            return ApiResponse.success(notification);
        } catch (Exception e) {
            logger.error("创建通知失败: " + e.getMessage(), e);
            return ApiResponse.error("创建通知失败: " + e.getMessage());
        }
    }

    /**
     * 创建关注的人发表评论的通知
     *
     * @param workId 作品ID
     * @param workTitle 作品标题
     * @param commentId 评论ID
     * @param commentContent 评论内容
     * @param fromUserId 评论者ID（关注的人）
     * @return 创建的通知
     */
    @Transactional
    public void createFollowingCommentNotification(Long workId, String workTitle, Long commentId,
                                                 String commentContent, Long fromUserId) {
        // 获取评论者的关注者列表
        List<Long> followers = userMapper.findFollowersByUserId(fromUserId);
        if (followers == null || followers.isEmpty()) {
            return;
        }

        // 获取评论者用户名
        User fromUser = userMapper.findById(fromUserId);
        String fromUsername = fromUser != null ? fromUser.getUsername() : "用户";

        // 为每个关注者创建通知
        for (Long followerId : followers) {
            // 创建通知
            Notification notification = new Notification();
            notification.setUserId(followerId);
            notification.setFromUserId(fromUserId);
            notification.setType("following_comment");
            notification.setContent(fromUsername + " 评论了作品 " + (workTitle != null ? workTitle : "未命名作品") +
                                  "：" + (commentContent.length() > 30 ? commentContent.substring(0, 30) + "..." : commentContent));
            notification.setResourceId(workId);
            notification.setIsRead(0);
            notification.setCreateTime(new Date());
            notification.setUpdateTime(new Date());

            notificationMapper.insert(notification);
        }
    }
}
